<template>
  <div class="report-list">
    <!-- 批量操作工具栏 -->
    <div style="margin-bottom: 10px" v-if="multipleSelection.length > 0">
      <el-button size="small" type="danger" @click="handleBatchDelete">
        批量删除 ({{ multipleSelection.length }})
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      :data="functionalData"
      @selection-change="handleSelectionChange"
      highlight-current-row
      ref="tableRef"
    >
      <el-table-column type="selection" width="50" />

      <el-table-column type="index" width="60" />

      <el-table-column label="用例名称" prop="case_name" min-width="180">
        <template #default="{ row }">
          <span class="case-name">{{ row.case_name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="方法" prop="method" width="80">
        <template #default="{ row }">
          <el-tag :type="getMethodType(row.method)" size="small">
            {{ row.method }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="状态码" prop="actual_status" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusCodeType(row.expected_status)" size="small">
            {{ row.actual_status }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="结果" prop="status" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)" size="small">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="耗时(s)" prop="duration_seconds" width="100">
        <template #default="{ row }">
          {{ row.duration_seconds }}
        </template>
      </el-table-column>

      <el-table-column label="吞吐量" prop="throughput_kbps" width="100">
        <template #default="{ row }"> {{ row.throughput_kbps }} Kbps </template>
      </el-table-column>

      <el-table-column label="响应大小" prop="response_size_bytes" width="120">
        <template #default="{ row }">
          {{ formatBytes(row.response_size_bytes) }}
        </template>
      </el-table-column>

      <el-table-column label="执行时间" prop="timestamp" min-width="160">
        <template #default="{ row }">
          {{ formatDate(row.timestamp) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="160">
        <template #default="{ row }">
          <el-button size="small" type="primary" text @click.stop="handleRowClick(row)">
            查看详情
          </el-button>
          <el-button size="small" type="danger" text @click.stop="handleDelete(row.report_id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import api from '@/services/api'
import { ElMessageBox, ElMessage } from 'element-plus'

const reports = ref([])
const router = useRouter()
const multipleSelection = ref([]) // 存储选中的行
const tableRef = ref() // 表格引用
import { useReportStore } from '@/stores/reportStore'

const reportStore = useReportStore()

const functionalData = computed(() => {
  return reportStore.functionalData
})

// 获取数据
async function fetchData() {
  try {
    const res = await api.get('/test-reports/')
    reportStore.functionalData = Array.from(res.data)
    console.log('res.data', res.data)
  } catch (error) {
    console.error('获取报告失败:', error)
    ElMessage.error('加载数据失败')
    reports.value = []
  }
}

// 多选变化
function handleSelectionChange(selection) {
  multipleSelection.value = selection
}

// 单条删除
async function handleDelete(reportId) {
  try {
    await ElMessageBox.confirm('确定要删除这条报告吗？', '警告', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await api.delete(`/test-reports/${reportId}/`) // 注意：结尾斜杠
    ElMessage.success('删除成功')
    fetchData() // 刷新列表
  } catch (error) {
    if (error.response?.status === 404) {
      ElMessage.warning('报告不存在')
    } else if (error === 'cancel') {
      // 用户取消
    } else {
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
async function handleBatchDelete() {
  const ids = multipleSelection.value.map((r) => r.report_id)
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${ids.length} 条报告吗？`, '警告', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    })

    // 批量删除：可以改为 POST /test-reports/delete-batch/ 或循环删除
    for (const id of ids) {
      await api.delete(`/test-reports/${id}/`)
    }

    ElMessage.success(`成功删除 ${ids.length} 条报告`)
    fetchData()
    // 清空选择
    tableRef.value.clearSelection()
  } catch (error) {
    if (error === 'cancel') return
    ElMessage.error('批量删除失败')
  }
}

// 行点击
function handleRowClick(row) {
  console.log('row', row)
  router.push(`/reports/detail/${row.report_id}`)
  // ✅ 把整个 row 对象保存到 sessionStorage
  sessionStorage.setItem('currentTestCaseReport', JSON.stringify(row))
}

// 工具函数（保持不变）
const getMethodType = (m) =>
  ({ GET: 'success', POST: 'primary', PUT: 'warning', DELETE: 'danger' })[m] || 'info'

const getStatusType = (s) => ({ PASS: 'success', FAIL: 'danger', ERROR: 'warning' })[s] || 'info'

const getStatusCodeType = (c) => (c >= 200 && c < 300 ? 'success' : c >= 400 ? 'danger' : 'warning')

const formatBytes = (bytes) => (bytes > 1024 ? `${(bytes / 1024).toFixed(1)}KB` : `${bytes}B`)

const formatDate = (iso) => new Date(iso).toLocaleString('zh-CN')

onMounted(() => {
  fetchData()
})
</script>
